package com.qf.blogsystem.core.controller;

import com.qf.blogsystem.entity.User;
import com.qf.blogsystem.service.UserService;
import com.qf.blogsystem.service.impl.UserServiceImpl;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 文件传输servlet
 */
@WebServlet("/FileServlet/*")
@MultipartConfig
public class FileServlet extends BaseServlet {
    /**
     * 创建用户业务层实现对象
     */
    private UserService userService = new UserServiceImpl();

    /**
     * 头像上传
     * @return String
     * @throws Exception
     */
    public String upload() throws Exception {
        //获取前端传递的二进制文件
        Part part = request.getPart("pngFile");
        //获取文件名称
        String fileName = part.getSubmittedFileName();
        //获取文件上传的位置
        String pngPath = request.getServletContext().getRealPath("png");
        //文件的路径
        String filePath = pngPath + File.separator + fileName;
        //把文件写入到指定位置
        part.write(filePath);
        //更新用户头像地址
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        boolean result = userService.updateHeaderUrl(loginUser.getId(), filePath);
        if (result){
            return outJson(200,"头像上传成功!");
        }else {
            return outJson(100,"头像上传失败!");
        }

    }

    /**
     * 显示头像
     * @throws Exception
     */
    public void showPng() throws Exception {
        //获取文件名
        String url = request.getParameter("fileName");
        //获取图片路径
        String pngPath = request.getServletContext().getRealPath("png");
        //根据路径创建流
        FileInputStream ips = new FileInputStream(pngPath + File.separator + url);
        //IO流拷贝,把ips中的内容拷贝response的流中
        IOUtils.copy(ips, response.getOutputStream());
    }
}
